<template>
	<el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false">
		<el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="100px" @keyup.enter="submitHandle()">
			<el-form-item label="主键" prop="id" v-if="false">
				<el-input v-model="dataForm.id" placeholder="主键"></el-input>
			</el-form-item>

			<el-form-item label="采购单号" prop="code">
				<el-input v-model="dataForm.code" placeholder="采购单号"></el-input>
			</el-form-item>
			<el-form-item label="申请日期" prop="requestDate">
				<el-input v-model="dataForm.requestDate" placeholder="申请日期"></el-input>
			</el-form-item>
			<el-form-item label="申请部门" prop="deptId">
				<el-input v-model="dataForm.deptId" placeholder="申请部门"></el-input>
			</el-form-item>
			<el-form-item label="申请人" prop="staffId">
				<el-input v-model="dataForm.staffId" placeholder="申请人"></el-input>
			</el-form-item>
			<el-form-item label="供应商" prop="supplier">
				<el-input v-model="dataForm.supplier" placeholder="供应商"></el-input>
			</el-form-item>
			<el-form-item label="附件" prop="fileUrl">
				<el-input v-model="dataForm.fileUrl" placeholder="附件"></el-input>
			</el-form-item>
			<el-form-item label="申请说明" prop="explanation">
				<el-input v-model="dataForm.explanation" placeholder="申请说明"></el-input>
			</el-form-item>
			<el-form-item label="合计数量" prop="total">
				<el-input v-model="dataForm.total" placeholder="合计数量"></el-input>
			</el-form-item>
			<el-form-item label="合计金额" prop="amount">
				<el-input v-model="dataForm.amount" placeholder="合计金额"></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" @click="submitHandle()">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus/es'
import { useAssetPurchaseApi, useAssetPurchaseSubmitApi } from '@/api/nb/asset/purchase'

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const dataFormRef = ref()

const dataForm = reactive({
	id: '',

	code: '',
	requestDate: '',
	deptId: '',
	staffId: '',
	supplier: '',
	fileUrl: '',
	explanation: '',
	total: '',
	amount: ''
})

const init = (id?: number) => {
	visible.value = true
	dataForm.id = ''

	// 重置表单数据
	if (dataFormRef.value) {
		dataFormRef.value.resetFields()
	}

	if (id) {
		getAssetPurchase(id)
	}
}

const getAssetPurchase = (id: number) => {
	useAssetPurchaseApi(id).then(res => {
		Object.assign(dataForm, res.data)
	})
}

const dataRules = ref({
})

// 表单提交
const submitHandle = () => {
	dataFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			return false
		}

		useAssetPurchaseSubmitApi(dataForm).then(() => {
			ElMessage.success({
				message: '操作成功',
				duration: 500,
				onClose: () => {
					visible.value = false
					emit('refreshDataList')
				}
			})
		})
	})
}

defineExpose({
	init
})
</script>
